﻿using System;
using System.Collections.Generic;
using System.Text;
using System.Threading;
using System.Collections;
using System.Reflection;
using System.Linq;
using UMC.Wiki.Entities;
using UMC.Web;

namespace UMC.Wiki.Activities
{
    class SubjectNavActivity : WebActivity
    {
        //System.di
        public static Project Dashboard(ulong newProjectId, UMC.Security.Identity user, out ulong PortfolioId)
        {
           

            var team = new Project
            {
                ModifiedTime = DateTime.Now,
                Id = newProjectId,//Utility.UInt64Parse(user.Id.Value),
                user_id = user.Id,
                Code = UMC.Data.Utility.Parse36Encode(user.Id.Value),
                CreationTime = DateTime.Now,
                MemberTotal = 1,
                Caption = user.Alias,
                Sequence = 0
            };

            DataFactory.Instance().Put(team);

            var p = new ProjectItem()
            {
                Id = UMC.Data.Utility.NewId(),
                Caption = "首页",
                Code = "Home",
                CreationTime = DateTime.Now,
                project_id = team.Id,
                Sequence = 0,
                user_id = user.Id,
            };
            DataFactory.Instance().Put(p);

            PortfolioId = UMC.Data.Utility.NewId();
            var portfolio = new Portfolio()
            {
                Id = PortfolioId,
                Caption = "随笔",
                SubjectTotal = 0,
                CreationTime = DateTime.Now,
                Sequence = 0,
                user_id = user.Id,
                project_id = team.Id,
                project_item_id = p.Id,
            };
            DataFactory.Instance().Put(portfolio);
            DataFactory.Instance().Put(new ProjectMember
            {
                project_id = team.Id,
                CreationTime = DateTime.Now,
                Alias = user.Alias,
                AuthType = WebAuthType.Admin,
                user_id = user.Id
            });

            var ax = DataFactory.Instance().Attention(user.Id.Value) ?? new Attention { Id = user.Id };
            DataFactory.Instance().Put(new Attention
            {
                Id = user.Id,
                ProjectTotal = (ax.ProjectTotal ?? 0) + 1
            });

            return team;


        }
        public override void ProcessActivity(WebRequest request, WebResponse response)
        {

            var user = this.Context.Token.Identity();


            var code = this.AsyncDialog("code", g =>
            {
                return this.DialogValue("none");
            });
            var redData = new WebMeta();

            var paths = new List<String>();
            var search = String.Empty;
            var sIndex = code.IndexOf('?');
            if (sIndex > 0)
            {
                search = code.Substring(sIndex + 1);

                paths.AddRange(code.Substring(0, sIndex).Split(new char[] { '/' }, StringSplitOptions.RemoveEmptyEntries));

            }
            else
            {
                paths.AddRange(code.Split(new char[] { '/' }, StringSplitOptions.RemoveEmptyEntries));
                search = String.Empty;

            }
            Project team = null;
            switch (paths[0])
            {
                case "UMC":
                    if (paths.Count > 2)
                    {
                        redData.Put("type", "nav");
                        switch (paths[1])
                        {
                            case "follow":
                                if (user.IsAuthenticated)
                                {
                                    response.Redirect(redData.Put("nav", paths[2]).Put("click", new UIClick(request.Model, "Team", "Project", paths[2], "Id", "follow")));

                                }
                                else
                                {
                                    response.Redirect(redData.Put("type", "login"));
                                }
                                break;
                        }
                        var ms = new WebMeta();
                        if (String.IsNullOrEmpty(search) == false)
                        {

                            var vs = System.Web.HttpUtility.ParseQueryString(search);
                            for (int i = 0; i < vs.Count; i++)
                            {
                                ms[vs.GetKey(i)] = vs[i];
                            }
                        }
                        var model = paths[1];
                        var cmd = paths[2];
                        paths.RemoveAt(0);
                        paths.RemoveAt(0);
                        paths.RemoveAt(0);
                        if (paths.Count > 0)
                        {
                            ms["__"] = String.Join("/", paths);
                        }

                        response.Redirect(redData.Put("click", new UIClick(model, cmd, ms)));
                    }
                    else
                    {
                        response.Redirect(redData.Put("type", "home"));
                    }
                    break;
                case "dashboard":
                    if (user.IsAuthenticated)
                    {
                        var type = this.AsyncDialog("type", "self");
                        switch (type)
                        {
                            case "project":
                                var userCode = Utility.UInt64Parse(user.Id.Value);
                                var projts = DataFactory.Instance().ProjectMember(user.Id.Value);
                                if (projts.Length == 0)
                                {
                                    this.AsyncDialog("Image", "System", "Image", new WebMeta("media_id", "https://res.apiumc.com/css/icon200.jpg").Put("id", userCode), true);
                                    team = Dashboard(userCode, user, out var PortfolioId);
                                }
                                else
                                {

                                    var pm = projts.FirstOrDefault(d => d.project_id == userCode) ?? projts.OrderByDescending(r => r.AuthType).First();
                                    team = DataFactory.Instance().Project(pm.project_id.Value);

                                }
                                break;
                            default:
                                response.Redirect(redData.Put("type", "dashboard"));
                                break;
                        }

                    }
                    else
                    {
                        response.Redirect(redData.Put("type", "login"));
                    }
                    break;

            }

            if (team == null)
            {
                team = DataFactory.Instance().Project(paths[0].ToLower());

                if (team == null)
                {
                    response.Redirect(redData.Put("type", "home"));

                }
            }
            var tAppKey = team.AppKey ?? Guid.Empty;
            if (tAppKey != Guid.Empty)
            {
                if (this.Context.AppKey.HasValue && this.Context.AppKey.Value != tAppKey)
                {
                    response.Redirect(redData.Put("type", "home"));
                }
            }



            var projects = DataFactory.Instance().ProjectItem(new Project { Id = team.Id });

            var clsName = "";
            var status = -1;
            var member = DataFactory.Instance().ProjectMember(team.Id.Value, user.Id.Value);

            if (member != null)
            {
                switch (member.AuthType)
                {
                    case WebAuthType.Admin:
                        clsName = "EditerItem";
                        status = 1;
                        break;
                    default:
                    case WebAuthType.Guest:
                        status = -1;
                        break;
                    case WebAuthType.User:
                        clsName = "EditerDoc";
                        status = 1;
                        break;
                }
            }
            var data = new List<WebMeta>();
            int pindex = 0;
            ProjectItem projectItem = null;
            foreach (var p in projects)
            {
                var meta = new WebMeta();
                meta.Put("id", p.Id).Put("text", p.Caption).Put("path", String.Format("{0}/{1}", team.Code, p.Code));


                if (p.Hide == true)
                {
                    switch (clsName)
                    {
                        case "EditerDoc":
                        case "EditerItem":
                        case "EditerAll":
                            meta.Put("cls", "warn");
                            break;
                        default:
                            meta.Put("cls", "hide");
                            break;
                    }
                    meta.Put("hide", true);
                }

                if (paths.Count > 1 && String.Equals(paths[1], p.Code, StringComparison.CurrentCultureIgnoreCase))
                {
                    projectItem = p;
                    pindex = data.Count;
                }
                data.Add(meta);
            }
            var webr = Web.WebResource.Instance();

            var menu = redData.Put("menu", data).Put("selectIndex", pindex).Put("text", team.Caption).Put("code", team.Code).Put("id", team.Id).Put("src", webr.ImageResolve(request.Url, team.Id.Value, "1", 4));

            menu["Auth"] = clsName;

            if (projects.Length > 0)
            {
                var pitem = projectItem == null ? projects[pindex] : projectItem;
                var subs = SubjectPortfolioSubActivity.Portfolio(team, pitem, status);
                menu.Put("subs", subs).Put("nav", String.Format("{0}/{1}", team.Code, pitem.Code));

            }

            switch (paths.Count)
            {
                case 1:
                    if (request.IsApp)
                    {
                        response.Redirect(request.Model, "ProjectUI", team.Id.ToString());
                    }
                    else
                    {
                        menu.Put("spa", new WebMeta().Put("path", team.Code).Put("id", team.Id).Put("type", "project"));
                    }
                    break;
                case 2:
                    if (projectItem != null)
                    {
                        if (request.IsApp)
                        {
                            response.Redirect(request.Model, "ProjectUI", new WebMeta().Put("Id", projectItem.project_id.ToString(), "CId", projectItem.Id.ToString(), "Type", "Portfolio", "selectIndex", "0"), true);

                        }
                        else
                        {
                            menu.Put("spa", new WebMeta().Put("path", String.Format("{0}/{1}", team.Code, projectItem.Code)).Put("id", projectItem.Id).Put("type", "item"));
                        }
                    };
                    break;
                case 3:

                    if (projectItem != null)
                    {
                        var sub = DataFactory.Instance().Subject(team.Id.Value, projectItem.Id.Value, paths[2]);
                        if (sub != null)
                        {
                            if (request.IsApp)
                            {
                                response.Redirect(request.Model, "UIData", sub.Id.ToString());
                            }
                            else
                            {
                                menu.Put("spa", new WebMeta().Put("id", sub.Id).Put("path", String.Format("{0}/{1}/{2}", team.Code, projectItem.Code, sub.Code)).Put("type", "subject"));
                            }
                        }
                    }
                    break;
            }
            if (user.IsAuthenticated)
            {
                menu.Put("IsAuthenticated", true);
            }
            response.Redirect(menu);


        }

    }
}